﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Xml.Linq;
using MiniDatabases;
using VEGA.Algorithm.Elements;

namespace VEGA.Algorithm
{
    internal class Evaluator
    {
        public List<Individual> Input { get; set; }
        public List<Individual> Output { get; set; }

        public int SimulationThreadCount { get; set; }

        public Evaluator()
        {
        }

        public void Run()
        {
            Output = Quantify();
            DataAccessObject(Output);
        }


        private List<Individual> Quantify()
        {
            double totalIpc = 0;
            double totalPower = 0;
            var evaluatedPopulation = new List<Individual>(Input);

            foreach (var individual in Input)
            {
                totalIpc += individual.Ipc;
                totalPower += individual.Power;
            }

            foreach (var individual in evaluatedPopulation)
            {
                individual.FitnessIpc = individual.Ipc/totalIpc;
                individual.FitnessPower = individual.Power/totalPower;
            }


            return evaluatedPopulation;
        }

        private static void DataAccessObject(IEnumerable<Individual> output)
        {
            var xmlDatabase = new XmlDatabase("database.xml");
            xmlDatabase.Open();
            xmlDatabase.Create("individuals", "ipc_score", "power_score", "configuration");

            foreach (var individual in output)
            {
                var values = new Dictionary<string, string>();
                values.Add("ipc_score", individual.Ipc.ToString("F6"));
                values.Add("power_score", individual.Power.ToString("F6"));
                values.Add("configuration", individual.Configuration.ToString());

                xmlDatabase.Insert("individuals", values);
            }

            xmlDatabase.Close();
        }
    }
}